<?php

namespace backend\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
use yii\web\UploadedFile;

/**
 * This is the model class for table "news".
 *
 * @property int $id
 * @property string $title
 * @property string $alias
 * @property string $description
 * @property string $prev_img
 * @property string $date_public
 * @property string $content
 * @property int $id_parent_department
 *
 * @property Department $parentDepartment
 */
class News extends \yii\db\ActiveRecord
{
    public $imageForCover;
    public $imagesForGallery;

    const BUCKET_NAME = 'ogikm-img-news';

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'news';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id_info_chanel'], 'integer'],
            [['date_public'], 'safe'],
            [['content'], 'string'],
            [['content', 'id_info_chanel', 'date_public'], 'required'],
            [['prev_img'], 'string', 'max' => 45],
            [['gallery_img'], 'string', 'max' => 512],
            [['imageForCover'], 'file', 'extensions' => 'jpg'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'prev_img' => 'Изображение для обложки',
            'date_public' => 'Дата публикации',
            'content' => 'Содержание',
            'imageForCover' => 'Изображение для обложки',
            'id_info_chanel' => 'Информационный канал',
            'gallery_img' => 'Галерея',
            'imagesForGallery' => 'Изображения для галлереи',
        ];
    }

    public function getInfoChanel()
    {
        return $this->hasOne(InfoChanel::className(), ['id' => 'id_info_chanel']);
    }

    public function beforeDelete()
    {
        if (!parent::beforeDelete()) {
            return false;
        }

        if($this->prev_img)
        {
            $this->deleteImageFile($this->prev_img);
        }

        if($this->gallery_img)
        {
            foreach(explode(',', $this->gallery_img) as $image)
            {
                $this->deleteImageFile($image);
            }
        }
        
        return true;
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }

        if($insert)
        {
            if($this->imageForCover)
            {
                $this->processCoverImage();   
            }
            if(!empty($this->imagesForGallery))
            {
                $this->processGalleryImages();
            }
        }
        else
        {
            if($this->imageForCover)
            {
                if($this->prev_img)
                {
                    $this->deleteImageFile($this->prev_img);
                }
                $this->processCoverImage();
            }
            if(!empty($this->imagesForGallery))
            {
                $this->processGalleryImages();
            }
        }
        
        return true;
    }

    private function deleteImageFile($fileName)
    {
        if($fileName)
        {
            $s3 = Yii::$app->get('s3');
            $s3->commands()->delete($fileName)->inBucket(self::BUCKET_NAME)->execute();
        }
    }

    public function deleteImageFromGallery($imageName)
    {
        $this->deleteImageFile($imageName);
        $this->gallery_img = implode(',', array_diff(explode(',', $this->gallery_img), [$imageName]));
    }

    public function processCoverImage()
    {
        $generatedName = $this->generateFileName($this->imageForCover, 'c');
        $this->prev_img = $generatedName;
        $this->uploadImage($this->imageForCover, $generatedName);
    }

    public function processGalleryImages()
    {
        if($this->gallery_img)
        {
            $generatedNamesArr = explode(',', $this->gallery_img);
        }
        else
        {
            $generatedNamesArr = array();
        }
        
        foreach ($this->imagesForGallery as $index => $image) 
        {
            $generatedName = $this->generateFileName($image, $index);
            array_push($generatedNamesArr, $generatedName);
            $this->uploadImage($image, $generatedName);
        }

        $this->gallery_img = implode(',', $generatedNamesArr);
    }

    private function uploadImage($file, $fileName)
    {
        if($file)
        {
            $s3 = Yii::$app->get('s3');
            $result = $s3->commands()->upload($fileName, $file->tempName)->inBucket(self::BUCKET_NAME)->withAcl('private')->execute();
        }
    }

    private function generateFileName($file, $postfix = '')
    {
        return uniqid() . $postfix . '.' . $file->extension;
    }
}
